/**
 * Copyright 2011 Enjoy Change, Inc. All rights reserved.
 * Use is subject to license terms.
 */
package com.enjoychange.enjoy.infrastructure.impl;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.enjoychange.common.tool.MD5Helper;
import com.enjoychange.core.dao.UniversalDao;
import com.enjoychange.enjoy.common.tool.SQLString;
import com.enjoychange.enjoy.domain.Account;
import com.enjoychange.enjoy.infrastructure.IAccountRepository;

/**
 * @author Administrator
 * @date   May 31, 2011
 */
@Repository
public class AccountRepository implements IAccountRepository {

	
	/* (non-Javadoc)
	 * @see com.enjoychange.enjoy.infrastructure.IAccountRepository#saveAccount()
	 */
	@Override
	public int saveAccount(Account account) {
		Map<String, Object> paras=new HashMap<String, Object>();
		//:email,:password,:firstname,:lastname
		paras.put("email", account.getEmail());
		String password=MD5Helper.encrypt(account.getPassword());
		paras.put("password", password);
		paras.put("firstname", account.getFirstname());
		paras.put("lastname", account.getLastname());
		
		return UniversalDao.executeUpdate(SQLString.ACCOUNT_INSERT_SQL,paras);

	}

	/* (non-Javadoc)
	 * @see com.enjoychange.enjoy.infrastructure.IAccountRepository#saveDeposit()
	 */
	@Override
	public void saveDeposit() {
		// TODO Auto-generated method stub

	}

	@Override
	@Transactional
	public boolean isAccountExist(Account account) {
		String sql=account.isNew()?SQLString.ACCOUNT_EXIST_SQL:SQLString.ACCOUNT_EXIST_UPDTE_SQL;
		
		Map<String, Object> paras=new HashMap<String, Object>();		
		paras.put("email", account.getEmail());
	    if(account.isNew()){
		   paras.put("id", account.getId());
	    }
		
		return UniversalDao.getNamedParameterJdbcTemplate().queryForInt(sql, paras)>0;
	}

	@Transactional
	private Account queryAccount(Map<String, Object> paras) {
		String sql = SQLString.ACCOUNT_QUERY_SQL;		

		ParameterizedRowMapper<Account> mapper = new ParameterizedRowMapper<Account>() {
			@Override
			public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
				Account account = new Account();
				account.setId(rs.getInt("id"));
				account.setPassword(rs.getString("password"));
				account.setEmail(rs.getString("email"));
				return account;
			}
		};

		return (Account) UniversalDao.getNamedParameterJdbcTemplate()
				.queryForObject(sql, paras, mapper);
    }

	@Override
	public String queryPasswordByEmail(final Account account) {
		Map<String, Object> paras = new HashMap<String, Object>();
		paras.put("email", account.getEmail());		
		return queryAccount(paras).getPassword();
	}

}
